<style lang="less">
  .left-container {
    width:100%;
    height: 100%;
    overflow:auto;
    min-height:100px;
    .gantt_layout_root {
      height: calc(~"100vh - 200px")!important;
    }
  }
  .nonworkday{
      background: #F0DFE5 !important;
  }
  .gantt_task_line, .gantt_line_wrapper {
    margin-top: -9px;
  }
  .gantt_side_content {
      margin-bottom: 7px;
  }
  .gantt_task_link .gantt_link_arrow {
      margin-top: -12px !important;
  }
  .gantt_side_content.gantt_right {
      bottom: 0;
  }
  .baseline {
    position: absolute;
    border-radius: 2px;
    opacity: 0.6;
    margin-top: -7px;
    height: 12px;
    background: #ffd180;
    border: 1px solid rgb(255,153,0);
  }
  .summary-row, .summary-row.odd {
    background-color: #EEEEEE !important;
    font-weight: bold;
  }
  .gantt_grid div, .gantt_data_area div {
    font-size: 12px;
  }
  .summary-bar {
    opacity: 0.4;
  }
  .gantt_task_cell.week_end {
    background-color: #EFF5FD;
  }
  .gantt_task_row.gantt_selected .gantt_task_cell.week_end {
    background-color: #F8EC9C;
  }
  .slack {
    position: absolute;
    border-radius: 0;
    opacity: 0.7;

    border: none;
    border-right: 1px solid #b6b6b6;
    margin-left: -2px;
    background: #b6b6b6;
    background: repeating-linear-gradient(
        45deg, #FFFFFF,
        #FFFFFF 5px,
        #b6b6b6 5px,
        #b6b6b6 10px
    );
  }
  .btn{
    font: 500 14px Roboto;
    border: 1px solid #D9D9D9;
    border-radius: 2px;
    background: #fff;
    padding: 4px 12px;
    margin: 0 5px;
    color: rgba(0,0,0,0.7);
    line-height: 20px;
    outline-color:#FFFAFA;
  }
  .complete_button{
    margin-top: 1px;
    background-image:url("v_complete.png");
    width: 20px;
  }
</style>
<template>
  <div :style="{border:'1px inset #D9D9D9',width:'99%'}">
    <Row>
      <Col :span="6">
        <Button v-if="defaultCfg.config.show_slack" @click="toggleSlack">显示裕度</Button>
        <Button v-if="defaultCfg.config.highlight_critical_path" @click="updateCriticalPath">显示关键路径</Button>
      </Col>
      <Col :span="6">
        <field-cell v-if="defaultCfg.config.group" :config="{type:'select',options:groupbyOptions}" style="width:200px" @change="groupBy"></field-cell>
      </Col>
      <Col :span="12">
        <Button @click="submit">保存</Button>
        <Button @click="exportExcel">导出Excel</Button>
        <Button @click="refresh">刷新</Button>
      </Col>
    </Row>
    <div ref="ganttEl" class="left-container"></div>
  </div>
</template>

<script>
  import gantt from 'public/3thComponents/gantt' ; // 引入模块
  import './ganttExport.js';
  import 'public/3thComponents/gantt/codebase/dhtmlxgantt.css';
  import FieldCell from "../basic/fieldCell";
  // import 'pub/gantt/codebase/dhtmlxgantt.js';
  export default {
    name: 'JGantt',
    components: {FieldCell},
    data() {
      let _this=this;
      return {
        groupbyOptions:[],
        defaultCfg:{
          rowLayout:{// the default layout
            css:"gantt_container",
            rows:[
                {
                  cols:[
                    {view:"grid",group:"grids",scrollX:"scrollHor",scrollY:"scrollVer"},//config: mainGridConfig,
                    {resizer:true,width:1},
                    {view:"timeline",scrollX:"scrollHor",scrollY:"scrollVer"},
                    {view:"scrollbar",id:"scrollVer",group:"vertical"}
                  ],
                  gravity:100
                }
            ],
          },
          rowResource:[// a custom layout
            {resizer:true,width: 1},
            {
              cols:[
                {view:"grid",group:"grids",id:"resourceGrid",bind:"resource",scrollY:"resourceVScroll"},//config:resourceGridConfig, 
                {resizer:true,width:1},
                {view:"timeline",id:"resourceTimeline",scrollX:"scrollHor",bind:"resource",bindLinks: null,scrollY:"resourceVScroll"},//layers: resourceLayers,
                {view:"scrollbar",id:"resourceVScroll",group:"vertical"}
              ],
              gravity:50
            }
          ],
          rowScroll:{view:"scrollbar",id:"scrollHor"},
          colLayout:{
            css:"gantt_container",
            cols:[
              {
                width:400,
                min_width:300,
                rows:[
                  {view:"grid",scrollable:true,scrollX:"gridScroll",scrollY:"scrollVer"},
                  {view:"scrollbar",id:"gridScroll",group:"horizontal"},
                     
                ]
              },
              {resizer:true,width:1},
              {
                rows:[
                  {view:"timeline",scrollX:"scrollHor",scrollY:"scrollVer"},
                  {view:"scrollbar",id:"scrollHor",group:"horizontal"}      
                ]
              }
            ]
          },
          colResource:[
            [{view:"grid",group:"grids",id:"resourceGrid",bind:"resource",scrollY:"resourceVScroll"},],
            [{view:"timeline",id:"resourceTimeline",scrollX:"scrollHor",bind:"resource",bindLinks: null,scrollY:"resourceVScroll"},]
          ],
          colScroll:{view: "scrollbar", id: "scrollVer"},
          columns:{
            wbs:{name:"wbs",label:"序号",resize:true,width:40, template:gantt.getWBSCode}, 
            text:{name:"text",label:"任务名称",tree:true,resize:true,width:"*"},
            holder:{name:"holder",label:"负责人",resize:true,width:"*"},
            workunitName:{name:"workunitName",label:"工位名称",resize:true,width:"*"},
            workunit:{name:"workunit",label:"工位ID",resize:true,width:"*",hide:true},
            // constraint_type:{name:"constraint_type",label:"约束",hide:true,resize:true,width:"*",align:"center"},
            // constraint_date:{name:"constraint_date",label:"约束时间",hide:true,resize:true,width:"*",align:"center"},
            planned_start:{name:"planned_start",label:"计划开始时间",hide:false,resize:true,width:"*",align:"center"},
            planned_end:{name:"planned_end",label:"计划结束时间",hide:false,resize:true,width:"*",align:"center"},
            start_date:{name:"start_date",label:"实际开始时间",resize:true,width:"*",align:"center"},
            end_date:{name:"end_date",label:"实际结束时间",hide:false,resize:true,width:"*",align:"center"},
            duration:{name:"duration",label:"期间",resize:true,align:"center"},
            progress:{name:"progress",label:"进度",resize:true,align:"center",template:item => {
              let num = (item.progress*100).toFixed(1);
              return num+'%';
            }},
            add:{name:"add",label:"",width:44}
          },
          sections:{
            reference:{name:"reference",label:"更多...",height:1,width:0,map_to:"task",type:"textarea",button:'reference'}, 
            task:{name:"task",label:"任务",height:30,map_to:"text",type:"textarea",focus:true}, 
            description:{name:"description",label:"描述",height:60,map_to:"desc",type:"textarea"},
            type:{name:"type",label:"任务类型",type:"typeselect",map_to:"type"}, 
            holder:{name:"holder",label:"负责人",type:"select",map_to:"holder"}, 
            workunit:{name:"workunit",label:"工位",type:"select",map_to:"workunit"}, 
            priority:{name:"priority",label:"优先级",height:22,map_to:"priority",type:"select", options:[
                {key:1,label:'High'},{key:2,label:'Normal'},{key:3,label:'Low'}]},
            split:{name:"split",label:'显示',type:"checkbox",map_to:"render",options:[{key:"split",label:"Split Task"}]},
            // constraint:{name:"constraint",label:"约束",type:"constraint"}, 
            actual:{name:"actual",label:"实际时间",height:25,map_to:"auto",type:"duration"},
            baseline:{name:"baseline",label:"计划时间",height:25,type:"duration",map_to:{start_date:"planned_start",end_date:"planned_end"}} 
          },
          sectionButtons:{
            save:{name:'gantt_save_btn',id:'icon_save',label:'保存',position:'left'},
            cancel:{name:'gantt_cancel_btn',id:'icon_cancel',label:'取消',position:'left'},
            complete:{name:'complete_button',id:'complete_button',label:'完成',position:'left'},
            delete:{name:'gantt_delete_btn',id:'icon_delete',label:'删除',position:'right'},
          },
          config:{
            /*date格式*/
            date_format:"%Y-%m-%d %H:%i:%s",
            /*附加标识线*/
            marker:true,
            autofit:true,
            autoscroll:true,
            autoscroll_speed:50,
            /*project 合并后依然具有收起图标*/
            open_split_tasks:true,
            /*auto scheduling*/
            auto_scheduling:true,
            /*drag-drop*/
            order_branch:'marker',
            order_branch_free:true,
            /*显示评估和可能区间*/
            highlight_critical_path:true,
            show_slack:true,
            /*设置工作时间*/
            work_time:true,
            duration_unit:'day',
            /*task操作*/
            cascade_delete:true,
            /*列头排序操作*/
            sort:true,
            group:true,
           // auto_scheduling:true,
            auto_scheduling_strict:true,
            auto_scheduling_initial:true,
            auto_scheduling_compatibility:true,
            auto_scheduling_descendant_links:true,
            refresh:true,
          }
        },
        gantt:null,
        ganttEl:null,
        // "minute", "hour", "day" (default), "week", "quarter", "month", "year"
        defaultScales:{
          year:{unit: "year", step: 1, format: function (date) {return _this.tools.formatter.year(date,"%YY")}},
          quarter:{unit: "quarter", step: 1, format: function(date){return "Q#"+_this.tools.formatter.quarter(date,"%EQ")}},
          yearquarter:{unit: "quarter", step: 1, format: function (date) {return _this.tools.formatter.year(date,"%YY")+" Q#"+_this.tools.formatter.quarter(date,"%EQ")}},
          month:{unit: "month", step: 1, format: function (date) {return _this.tools.formatter.month(date,"%EM")}},
          yearmonth:{unit: "month", step: 1, format: function (date) {return _this.tools.formatter.year(date,"%YY")+"-"+_this.tools.formatter.month(date,"%EM")}},
          yearquartermonth:{unit: "month", step: 1, format: function (date) {return _this.tools.formatter.year(date,"%YY")+" Q#"+_this.tools.formatter.quarter(date,"%EQ")+"-"+_this.tools.formatter.month(date,"%EM")}},
          quartermonth:{unit: "month", step: 1, format: function (date) {return " Q#"+_this.tools.formatter.quarter(date,"%EQ")+"-"+_this.tools.formatter.month(date,"%EM")}},
          week:{unit: "week", step: 1, format: function (date) {return "Week #" + gantt.date.getWeek(date)}},
          workday:{unit: "day", step: 1, format: "%D", css: function(date){
              let dateToStr = gantt.date.date_to_str("%D");
              if (dateToStr(date) == "Sun"||dateToStr(date) == "Sat"){
                return "nonworkday";
              }else{
                return "";
              } 
            }
          },
          day:{unit: "day", step: 1, format: function(date) {return _this.tools.formatter.day(date,"%EN")}},
          date:{unit: "day", step: 1, format: function (date) {return _this.tools.formatter.date(date,"%DD")}},
          daydate:{unit: "day", step: 1, format: function (date) {return _this.tools.formatter.date(date,"%DD")+","+_this.tools.formatter.day(date,"%EN")}},
          yearmonthdate:{unit: "day", step: 1, format: function (date) {return _this.tools.formatter.year(date,"%YY")+"-"+_this.tools.formatter.month(date,"%EM")+"-"+_this.tools.formatter.date(date,"%DD")}},
          hour:{unit: "hour", step: 1, format: function(date) {return _this.tools.formatter.hour(date,"%HH")}},
          minute:{unit: "minute", step: 1, format: function(date) {return _this.tools.formatter.minute(date,"%MM")}},
        },
        defaultTpl:{}
      }
    },
    props:{
      isToolbar:{
        default:true
      },
      vm:{
        default:function(){
          return {};
        }
      },
      layout:{
        default:function(){
          return {
            type:'row',
            definedDef:false,//false:使用缺省定义；{...}:自定义
            additional:false,//false:不使用附加图；[]:使用缺省资源；[...]:自定义；
          }
        }
      },
      columns:{
        default:function(){
          return false;
        }
      },
      sections:{
        default:function(){
          return false;
        }
      },
      sectionButtons:{
        default:function(){
          return false;
        }
      },
      holiday:{
        default:function(){
          return [];
        }
      },
      scalesPattern:{
        default:function(){
          return [];
        }
      },
      scales:{
        default:function(){
          return [];
        }
      },
      config:{
        default:function(){
          return {}
        }
      },
      data:{
        default:function(){
          return {tasks:[],links:[]};
        }
      },
      tpl:{
        default:function(){
          return {};
        }
      },
    },
    mounted() {
      // let _this=this;
      // this.init();
      // this.gantt=gantt;
      // this.ganttEl=this.$refs._ganttEl;
      // Object.assign(this.vm,{
      //   gantt:gantt,
      //   self:this
      // });
      // this.$emit('update:vm',this.vm);
      this.$modelObject.create('taskModel',{el:this.$refs.ganttEl})
    },
    methods:{
      getDefault(){
        return this.definedDef;
      },
      initLayout(){
          let resourceConfig = {
              scale_height: 30,
              scales: [
                  {unit: "day", step: 1, date: "%d %M"}
              ],
              columns: [
                  {
                      name: "name", label: "Name", tree:true, width:250, template: function (resource) {
                          return resource.text;
                      }, resize: true
                  },
                  {
                      name: "allocated", label: "Allocated", align:"left", width:100, template: function (resource) {
                          var assignments = gantt.getResourceAssignments(resource.id);
                          var result = 0;
                          assignments.forEach(function(assignment){
                              var task = gantt.getTask(assignment.task_id);
                              if(resource.type == "work"){
                                  result += task.duration * assignment.value;
                              }else{
                                  result += assignment.value * 1;
                              }
                          });

                          if(resource.type == "work"){
                              result = "<b>" +result +  "</b> hours";
                          }else{
                              result = "<b>" +result + "</b> " + resource.unit;
                          }

                          return result;
                      }, resize: true
                  }
              ]
          };
        let type=this.layout.type=='row'||this.layout.type=='col'?this.layout.type:'row';
        let layout=this.defaultCfg[type+'Layout'];
        if(this.layout.definedDef){
          Object.assign(layout,this.layout.definedDef);
        };
        if(this.layout.hasAdditional){
          if(type=='row'){
            if(this.layout.additional.length==0){
              this.defaultCfg.rowResource.config = resourceConfig;
              layout.rows=layout.rows.concat(this.defaultCfg.rowResource,this.defaultCfg.rowScroll);
            }else{
              layout.rows=layout.rows.concat(this.layout.additional,this.defaultCfg.rowScroll);
            }
          }
        }else{
          layout.rows=layout.rows.concat(this.defaultCfg.rowScroll);
        };
        return layout;
      },
      initColumns(){
        let columns=[];
        if(this.columns==false){
          columns=Object.values(this.defaultCfg.columns);
        }else{
          Object.keys(this.defaultCfg.columns).map(key=>{
            if(Object.keys(this.columns).includes(key)){
              if(this.columns[key]===true||this.columns[key]===false){
                columns.push(Object.assign({},this.defaultCfg.columns[key],{hide:!this.columns[key]}));
              }else if(this.columns[key]!==null){
                columns.push(Object.assign({},this.defaultCfg.columns[key],this.columns[key]));
              }
            }else{
              columns.push(Object.assign({},this.defaultCfg.columns[key]));
            }
          });
          let definedCol=[];
          Object.keys(this.columns).map(key=>{
            if(!Object.keys(this.defaultCfg.columns).includes(key)){
              let item=Object.assign({},this.columns[key],{name:key});
              definedCol.splice(item.order,0,item);
            }
          });
          let addItem;
          if(columns[columns.length-1].name='add'){
              addItem=columns[columns.length-1];
            columns.pop();
            columns=columns.concat(definedCol);
            columns.push(addItem);
          }else{
            columns=columns.concat(definedCol);
          }
        };
        return columns;
      },
      initSections(){
        let sections=[];
        if(this.sections==false){
          sections=Object.values(this.defaultCfg.sections);
        }else{
          Object.keys(this.defaultCfg.sections).map(key=>{
            if(Object.keys(this.sections).includes(key)){
              if(this.sections[key]!==true&&this.sections[key]!==false){
                sections.push(Object.assign({},this.defaultCfg.sections[key],this.sections[key]));
              }
            }else{
              sections.push(Object.assign({},this.defaultCfg.sections[key]));
            }
          });
        };
        sections.map(item=>{
          if(Object.keys(item).includes('button')){
            gantt.locale.labels['button_'+item.button] = item.label;
            gantt.locale.labels['section_'+item.name] = item.label;
          }else{
            gantt.locale.labels['section_'+item.name] = item.label;
          }
        });
        let leftbuttons=[];
        let rightbuttons=[];
        if(this.sectionButtons===false){
          Object.values(this.defaultCfg.sectionButtons).map(item=>{
            if(item.position=='left'){
              leftbuttons.push(item.name);
            }else{
              rightbuttons.push(item.name);
            };
            gantt.locale.labels[item.id]=item.label;
          })
        };
        gantt.config.buttons_left=leftbuttons;
        gantt.config.buttons_right=rightbuttons;
        return sections;
      },
      initPlanned(){
        gantt.attachEvent("onTaskLoading", function(task){
          task.planned_start = gantt.date.parseDate(task.planned_start, "xml_date");
          task.planned_end = gantt.date.parseDate(task.planned_end, "xml_date");
          return true;
        });
        gantt.addTaskLayer({
          renderer: {
            render: function draw_planned(task) {
              if (task.planned_start && task.planned_end) {
                let sizes = gantt.getTaskPosition(task, task.planned_start, task.planned_end);
                let el = document.createElement('div');
                el.className = 'baseline';
                el.style.left = sizes.left + 'px';
                el.style.width = sizes.width + 'px';
                el.style.top = sizes.top + gantt.config.task_height + 13 + 'px';
                return el;
              }
              return false;
            },
            // define getRectangle in order to hook layer with the smart rendering
            getRectangle: function(task, view){
              if (task.planned_start && task.planned_end) {
                return gantt.getTaskPosition(task, task.planned_start, task.planned_end);
              }
              return null;
            }
          }
        });
        gantt.config.task_height=16;
        gantt.config.row_height=40;
      },
      initPlugin(){
        let plugins={};
        if(gantt.config.auto_scheduling){
          plugins['auto_scheduling']=true;
        };
        if(gantt.config.highlight_critical_path){
          plugins['critical_path']=true;
        };
        if(gantt.config.group){
          plugins['grouping']=true;
        };
        if(gantt.config.marker){
          plugins['marker']=true;
        }
        gantt.plugins(plugins);
        if(plugins.auto_scheduling){
          gantt.config.auto_scheduling = true;
        }
        let dateToStr = gantt.date.date_to_str(gantt.config.task_date);
        gantt.addMarker({  
          start_date: new Date(), 
          css: "today", 
          text: "Now", 
          title:"今天"+dateToStr(new Date()) 
        });
      },
      initSlack(){/* show slack */
        let totalSlackColumn = {
          name: "totalSlack",
          align: "center",
          resize: true,
          width: 70,
          hide:true,
          label: "Total slack",
          template: function(task) {
            if (gantt.isSummaryTask(task)) {
              return "";
            }
            return gantt.getTotalSlack(task);
          }
        }
        let freeSlackColumn = {
          name: "freeSlack",
          align: "center",
          resize: true,
          width: 70,
          hide:true,
          label: "Free slack",
          template: function(task) {
            if (gantt.isSummaryTask(task)) {
              return "";
            }
            return gantt.getFreeSlack(task);
          }
        };

        gantt.config.columns = gantt.config.columns.concat([freeSlackColumn,totalSlackColumn]);

        gantt.config.show_slack = false;
        gantt.addTaskLayer(function addSlack(task) {
          if (!gantt.config.show_slack) {
            return null;
          }

          let slack = gantt.getFreeSlack(task);

          if (!slack) {
            return null;
          }

          let state = gantt.getState().drag_mode;

          if (state == 'resize' || state == 'move') {
            return null;
          }

          let slackStart = new Date(task.end_date);
          let slackEnd = gantt.calculateEndDate(slackStart, slack);
          let sizes = gantt.getTaskPosition(task, slackStart, slackEnd);
          let el = document.createElement('div');

          el.className = 'slack';
          el.style.left = sizes.left + 'px';
          el.style.top = sizes.top + 2 + 'px';
          el.style.width = sizes.width + 'px';
          el.style.height = sizes.height + 'px';

          return el;
        });
      },
      initWorkTime(){
        if(this.defaultCfg.config.work_time){
          if(this.holiday.length>0){
            this.holiday.map((date)=>{
              gantt.setWorkTime({date:new Date(date), hours:false})
            })
          }
        };
        gantt.templates.timeline_cell_class = function (task, date) {
          if (!gantt.isWorkTime(date)) {
            return ("week_end");
          }
          return "";
        };
      },
      initGroup(){
        let groupbyOptions=[{label:'(取消分组)',value:'false'}];
        if(gantt.config.group==true){
          gantt.config.columns.map(item=>{
            if(item.name!='add'){
              groupbyOptions.push({label:item.label,value:item.name})
            }
          })
        }else{
          groupbyOptions=groupbyOptions.concat(gantt.config.group)
        }
        this.groupbyOptions=groupbyOptions;
        gantt.templates.task_row_class = function (start, end, task) {
          if (task.$virtual)
            return "summary-row"
        };
        gantt.templates.task_class = function (start, end, task) {
          if (task.$virtual)
            return "summary-bar";
        };
      },
      initScales(){
        let scalesPattern=["year","month","date"];
        let scales=[];
        let _this=this;
        if(this.scales.length>0){
          scales=this.scales;
        }else{
          if(this.scalesPattern.length!==0){
            scalesPattern=this.scalesPattern;
          };
          scalesPattern.forEach(function(item){
            if(_this.defaultScales[item]){
              scales.push(_this.defaultScales[item]);
            }
          });
          gantt.config.scale_height=this.scales.length*25<50?50:this.scales.length*25;
          gantt.config.scales=scales;

        }
      },
      initTpl(){
        let tpl={text:'',id:'',parent:'',link:'',start_date:'',end_date:'',planned_start:'',planned_end:'',duration:0,progress:0,holder:'',workunit:'',type:''};
        if(Object.keys(this.tpl).length>0){
          tpl=this.tpl;
        };
          tpl['id']='';
          tpl['parent']='';
          tpl['link']='';
          this.defaultTpl=tpl;
      },
      initEvent(){
        let _this=this;
        gantt.form_blocks.textarea.button_click = function(index,button,shead,sbody){
          let id = gantt.getState().lightbox;
          let task=gantt.getTask(id);
          _this.$emit('reference',gantt,id,task,_this.data);
        };
        gantt.attachEvent("onLightboxButton", function(button_id, node, e){
          if(button_id == "complete_button"){
            let id = gantt.getState().lightbox;
            gantt.getTask(id).progress = 1;
            gantt.updateTask(id);
            gantt.hideLightbox();
          };

        });
        gantt.attachEvent("onAfterTaskAdd", function(id,item){
          _this.getData();
          _this.$emit('addTask',gantt,id,item,_this.data);
        });
        gantt.attachEvent("onAfterTaskUpdate", function(id,item){
          _this.getData();
          _this.$emit('updateTask',gantt,id,item,_this.data);
        });
        gantt.attachEvent("onAfterTaskDelete", function(id,item){
          _this.getData();
          _this.$emit('deleteTask',gantt,id,item,_this.data);
        });
        gantt.attachEvent("onAfterLinkAdd", function(id,item){
          _this.getData();
          _this.$emit('addLink',gantt,id,item,_this.data);
        });
        gantt.attachEvent("onAfterLinkDelete", function(id,item){
          _this.getData();
          _this.$emit('deleteLink',gantt,id,item,_this.data);
        });
        gantt.attachEvent("onAfterLinkUpdate", function(id,item){
          _this.getData();
          _this.$emit('updateLink',gantt,id,item,_this.data);
        });
      },
      init(){
        gantt.plugins({auto_scheduling:true});
        let config={
          layout:this.initLayout(),
          columns:this.initColumns(),
          // lightbox:{
          //   sections:this.initSections(),
          // },
        };
        Object.assign(gantt.config,this.defaultCfg.config,config,this.config);
        // this.initPlugin();
        // this.initWorkTime();
        // this.initGroup();
        // this.initScales();
        // this.initTpl();
        //
        // gantt.$resourcesStore = gantt.createDatastore({
        //   name: 'resource',
        //   type: "treeDatastore",
        //   initItem: function (item) {
        //       item.parent = item.parent || gantt.config.root_id;
        //       item[gantt.config.resource_property] = item.parent;
        //       item.open = true;
        //       return item;
        //   }
        // });
        // gantt.$resourcesStore.attachEvent("onFilterItem", function(id, item) {
        //   return gantt.getResourceAssignments(id).length > 0;
        // });
        gantt.init(this.$refs.ganttEl);
        //
        // gantt.$resourcesStore.attachEvent("onParse", function(){
        //   var people = [];
        //   gantt.$resourcesStore.eachItem(function(res){
        //       if(!gantt.$resourcesStore.hasChild(res.id)){
        //           var copy = gantt.copy(res);
        //           copy.key = res.id;
        //           copy.label = res.text;
        //           people.push(copy);
        //       }
        //   });
        //   gantt.updateCollection("people", people);
        // });
        // gantt.attachEvent("onParse", function(){
        //   gantt.render();
        // });
        // gantt.$resourcesStore.parse([
        //   {id: 1, text: "panhao", unit:"hours/day", default_value:8, type:"work"},
        //   {id: 2, text: "yangxiaopei", unit:"hours/day", default_value:8, type:"work"},
        //   {id: 3, text: "wangtao", unit:"hours/day", default_value:8, type:"work"},
        // ]);
        //
        // gantt.resetLayout();
        // this.initPlanned();
        // this.initSlack();
        // gantt.parse(this.data);
        // this.initEvent();
      },
      toggleSlack(e) {
        if (e.currentTarget.value=="显示裕度") {
          e.currentTarget.value = "隐藏裕度";
          //declaring custom config
          gantt.config.show_slack = true;
        } else {
          e.currentTarget.value = "显示裕度";
          gantt.config.show_slack = false;
        }
        gantt.render();
      },
      updateCriticalPath(e) {
        if (e.currentTarget.value=="显示关键路径") {
          e.currentTarget.value = "隐藏关键路径";
          gantt.config.highlight_critical_path = true;
        } else {
          e.currentTarget.value = "显示关键路径";
          gantt.config.highlight_critical_path = false;
        }
        gantt.render();
      },
      groupBy(v){
        if(v=='false'){
          gantt.groupBy(false);
          return;
        };
        let m=false;
        let mapName='';
        let property=v;
        gantt.config.columns.map(item=>{
          if(item.name===v){
            if(Object.keys(item).includes('mapOption')){
              m={};
              mapName=item.mapName;
              property=mapName;
              item.mapOption.map(mapO=>{
                m[mapO.key]=mapO;
              })
            }
          }
        });
        let p={};
        if(m){
          this.data.tasks.map(item=>{
            if(!Object.keys(p).includes(item[mapName])){
              p[item[mapName]]={key:item[mapName],label:m[item[mapName]].label}
            }
          })
        }else{
          this.data.tasks.map(item=>{
            if(!Object.keys(p).includes(item[v])){
              p[item[v]]={key:item[v],label:item[v]}
            }
          });
        }
        let groups=Object.values(p);
        gantt.groupBy({
          relation_property:property,
          groups:groups,
          group_id:"key",
          group_text:"label"
        });
      },
      getData(){
        // this.$nextTick(()=>{
          let tasks=gantt.getTaskByTime();
          let links=gantt.getLinks();
          let newtasks=[];
          let newlinks=[];
          if(tasks.length>0){
            tasks.map(item=>{
              newtasks.push(this.tools.lodash.merge(this.tools.lodash.cloneDeep(this.defaultTpl),item));
            });  
          };
          let dateToStr = gantt.date.date_to_str("%Y-%m-%d %H:%i");
          let formattasks=[];
          newtasks.map(item=>{
            Object.keys(item).map(key=>{
              if(['start_date','end_date','planned_start','planned_end'].includes(key)){
                item[key]=dateToStr(item[key]);
              }
            })
            formattasks.push(item);
          })
          if(links.length>0){
            links.map((item,index)=>{
              newlinks.push(Object.assign({},item,{id:index+1}))
            })
          }
          this.$set(this.data,'tasks',formattasks);
          this.$set(this.data,'links',newlinks);

        // })
      },
      submit(e){
        this.getData();
        this.$emit('submit',gantt,this.data);
      },
      refresh(){
        gantt.render();
      },
      exportExcel(){
        let col = this.tools.clone(gantt._serialize_columns());
        gantt.config.columns.forEach(c => {
          if(c.hide === true){
            let i = col.findIndex(f => c.name === f.id);
            if(i>-1){
              col.splice(i,1);
            }
          }
        })
        col.forEach(c =>{
          if(c.id === "planned_start" || c.id === "planned_end"){
            c.type = 'date';
          }
        })
        let exCol = col.filter(c => c.id !== '_11' && c.id !== "_12");
        gantt.exportToExcel({
          columns:exCol,
          date_format:'yyyy-mm-dd hh:mm:ss'
        });
      }
    }
  }
</script>